package cn.regexp.web.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.regexp.domain.ShopCanteen;
import cn.regexp.service.ICanteenService;
import cn.regexp.utils.JsonResult;
import cn.regexp.utils.RedisKeys;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("canteens")
public class CanteenController {
    @Autowired
    private ICanteenService canteenService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("/queryCanteen")
    @ApiOperation(value = "查询餐厅", notes = "查询餐厅")
    public JsonResult<List<ShopCanteen>> queryCanteen() {
        // 从 redis 中获取餐厅信息
        Map<Object, Object> objectMap = redisTemplate.opsForHash().entries(RedisKeys.CANTEEN_INFO.join());
        List<ShopCanteen> canteens = new ArrayList<>();
        // 若 redis 中不存在餐厅信息，则直接查询数据库
        if (ObjectUtil.isNotEmpty(objectMap)) {
            Set<Object> keySet = objectMap.keySet();
            for (Object key : keySet) {
                ShopCanteen shopCanteen = JSON.parseObject(objectMap.get(key).toString(), ShopCanteen.class);
                canteens.add(shopCanteen);
            }
        } else {
            canteens = canteenService.queryCanteen();
        }
        canteens.sort(Comparator.comparing(ShopCanteen::getId));
        return  JsonResult.success(canteens);
    }

}
